
package cz.vitsol.dovweb.portlet.alert;

import java.io.IOException;
import java.util.List;
import java.util.Vector;

import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portlet.announcements.model.AnnouncementsEntry;
import com.liferay.portlet.announcements.service.AnnouncementsEntryLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class AlertWatchdogPortlet
 */
public class AlertWatchdogPortlet extends MVCPortlet {

	private final static Log LOGGER = LogFactory.getLog(AlertWatchdogPortlet.class);
	private final static List<String> BUFF = new Vector<String>();

	@Override
	public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
		throws IOException, PortletException {

		LOGGER.info("doView");

		AlertBean bean = new AlertBean();

		loadPendingAlerts(renderRequest.getPortletSession().getId(), bean);

		renderResponse.setContentType("text/html");
		renderRequest.setAttribute("alertsBean", bean);
		include(getInitParameter("view-template"), renderRequest, renderResponse);

	}

	/**
	 * Pro zadane sessionID nacte do beany titlky a obsahy dosud neprectenych
	 * platnych alertu.
	 * 
	 * @param sessionID
	 * @return
	 */
	private void loadPendingAlerts(String sessionID, AlertBean bean) {

		long time = System.currentTimeMillis();
		
		List<AnnouncementsEntry> res;

		try {
			res =
				AnnouncementsEntryLocalServiceUtil.getAnnouncementsEntries(QueryUtil.ALL_POS, QueryUtil.ALL_POS);

			for (AnnouncementsEntry entry : res) {

				if (entry.isAlert()) {

					// aktualne platny alert?
					if (entry.getExpirationDate().getTime() >= time && entry.getDisplayDate().getTime() <= time) {

						// dosud nezobrazeny v ramci session? nImfVkUCPLxq
						if (isUnread(entry.getUuid(), sessionID)) {
							bean.addAlert(entry.getTitle(), entry.getContent());
							
							// nasledujici return zabezpeci prave jeden alert zaslany ke zobrazeni, jinak by se nacetl cely seznam (druha
							// mozna stragie zpracovani alertu
							return;
						}
					}
				}
			}
		}
		catch (SystemException e) {
			LOGGER.error("Nelze nacist alerty", e);;
		} finally {
			res = null;
		}
		

	}

	/**
	 * Vraci true, pokud dany alert nebyl dosud v ramci session prezentovan,
	 * jinak false.
	 * 
	 * @param alertID
	 * @param sessionID
	 * @return
	 */
	private boolean isUnread(String alertID, String sessionID) {

		String klic = sessionID + alertID;

		synchronized (BUFF) {

			if (BUFF.contains(klic)) {
				return false;
			}
			else {
				BUFF.add(klic);
				return true;
			}

		}

	}

}
